﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UpdateTool
{
    public class Download
    {
        public Download()
        {

        }

        private void detail(string path)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(path);
            Console.WriteLine("最后修改时间：" + fi.LastWriteTime.ToString());//最后修改时间
            Console.WriteLine("最后访问时间：" + fi.LastAccessTime.ToString());//最后访问时间
            Console.WriteLine("文件创建时间：" + fi.CreationTime.ToString());//文件创建时间
            Console.WriteLine("文件大小：" + fi.Length.ToString());//文件大小
            Console.WriteLine("文件属性：" + fi.Attributes);//文件属性
        }
        //C#拷贝文件
        private void copy(string path_source, string path_target)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(path_source);
            fi.CopyTo(path_target, true);
        }

        //C#删除文件
        private void delete(string path)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(path);
            fi.Delete();
        }

        /// <summary>
        /// http下载文件
        /// </summary>
        /// <param name="url">下载文件地址</param>
        /// <param name="path">文件存放地址，包含文件名</param>
        /// <returns></returns>
        public bool HttpDownload(string url, string path)
        {
            //string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp";//Application.StartupPath + @"\Config.ini"
            string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp";
            System.IO.Directory.CreateDirectory(tempPath);  //创建临时文件目录
            string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(path) + ".temp"; //临时文件
            if (System.IO.File.Exists(tempFile))
            {
                System.IO.File.Delete(tempFile);    //存在则删除
            }
            try
            {
                if (url.ToLower().StartsWith("http://"))
                {
                    FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    // 设置参数
                    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                    //发送请求并获取相应回应数据
                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    //直到request.GetResponse()程序才开始向目标网页发送Post请求
                    Stream responseStream = response.GetResponseStream();
                    //创建本地文件写入流
                    //Stream stream = new FileStream(tempFile, FileMode.Create);
                    byte[] bArr = new byte[1024];
                    int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                    while (size > 0)
                    {
                        //stream.Write(bArr, 0, size);
                        fs.Write(bArr, 0, size);
                        size = responseStream.Read(bArr, 0, (int)bArr.Length);
                    }
                    //stream.Close();
                    fs.Close();
                    responseStream.Close();
                    //System.IO.File.Move(tempFile, path);
                    return true;
                }
                else if (url.ToLower().StartsWith("https://"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                    //httpPost.setHeader("Accept-Encoding", "identity");
                    //request.Headers.Add("Accept-Encoding", "gzip,deflate");
                    request.Headers.Add("Accept-Encoding", "identity");
                    request.Method = "HEAD";
                    request.ProtocolVersion = HttpVersion.Version10;

                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    Stream stream = response.GetResponseStream();

                    FileStream fs = new FileStream(tempFile, FileMode.Create);

                    BinaryWriter bw = new BinaryWriter(fs);
                    BinaryReader br = new BinaryReader(stream);

                    byte[] nbytes = new byte[2048];
                    int nReadSize = 0;
                    nReadSize = br.Read(nbytes, 0, 2048);
                    while (nReadSize > 0)
                    {
                        bw.Write(nbytes, 0, nReadSize);
                        nReadSize = br.Read(nbytes, 0, 2048);
                    }
                    stream.Close();
                    bw.Close();
                    br.Close();
                    return true;
                }
                else if (url.ToLower().StartsWith("ftp://"))
                {
                    FtpWebRequest reqFTP;
                    FileStream outputStream = new FileStream(tempFile, FileMode.Create);
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(url);
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                    reqFTP.UseBinary = true;
                    reqFTP.Credentials = new NetworkCredential("root", "");//ftp用户名和ftp密码
                    reqFTP.UsePassive = false;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    Stream ftpStream = response.GetResponseStream();
                    long cl = response.ContentLength;
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();

                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取网络文件的属性
        /// </summary>
        /// <param name="URL"></param>
        /// <returns></returns>
        public long GetInfo(string URL)
        {
            //string Results = "";
            //string filetype = URL.Substring(URL.LastIndexOf(".") + 1, (URL.Length - URL.LastIndexOf(".") - 1));
            //Results = "类型：" + filetype.ToUpper();
            //string filename = URL.Substring(URL.LastIndexOf("/") + 1, (URL.Length - URL.LastIndexOf("/") - 1));
            //Results += "|名称：" + filename;
            long ContentL = 0;
            if (URL.ToLower().StartsWith("http://"))
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

                request.MaximumAutomaticRedirections = 4;
                request.MaximumResponseHeadersLength = 4;
                request.Credentials = CredentialCache.DefaultCredentials;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                ContentL = response.ContentLength;
                response.Close();

                //Results += "|大小：" + GetSize(ContentL) + "|额外信息：" + response.Server;
            }
            else if (URL.ToLower().StartsWith("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
                //httpPost.setHeader("Accept-Encoding", "identity");
                //request.Headers.Add("Accept-Encoding", "gzip,deflate");
                request.Headers.Add("Accept-Encoding", "identity");
                request.Method = "HEAD";
                request.ProtocolVersion = HttpVersion.Version10;
                
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                WebHeaderCollection colHeader = response.Headers;
                string s = colHeader.Get("Content-Length");
                ContentL = response.ContentLength;
                response.Close();
                //Results += "|大小：" + GetSize(ContentL) + "|额外信息：" + response.Server;
                //var length = 0l;
            }
            else if (URL.ToLower().StartsWith("ftp://"))
            {

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(URL);
                request.Method = WebRequestMethods.Ftp.GetFileSize;
                request.UseBinary = true;
                FtpWebResponse response = null;
                response = (FtpWebResponse)request.GetResponse();
                Stream Fs = response.GetResponseStream();
                ContentL = response.ContentLength;
                Fs.Close();
                response.Close();
                //Results += "|大小：" + GetSize(ContentL) + "|额外信息：" + response.WelcomeMessage;
            }
            else
            {
                //Results += "|大小：无法检测";
            }
            return ContentL;
            //return Results;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受
        }

        //大小转化
        private string GetSize(long L)
        {
            float result;
            string re = "";
            if (L >= 1073741824)
            {
                result = L / 1073741824.00F;
                re = "GB";
            }
            else if (L >= 1048576)
            {
                result = L / 1048576.00F;
                re = "MB";
            }
            else
            {
                result = L / 1024.00F;
                re = "KB";
            }
            string File_Size = result.ToString("0.00");
            return (File_Size + re);
        }

        ///
        ///下载文件方法
        ///
        ///文件保存路径和文件名
        ///返回服务器文件名
        ///
        public bool DeownloadFile(string strFileName, string file)
        {
            bool flag = false;
            //打开上次下载的文件
            long SPosition = 0;
            //实例化流对象
            FileStream FStream;
            //判断要下载的文件夹是否存在
            if (File.Exists(strFileName))
            {
                //打开要下载的文件
                FStream = File.OpenWrite(strFileName);
                //获取已经下载的长度
                SPosition = FStream.Length;
                FStream.Seek(SPosition, SeekOrigin.Current);
            }
            else
            {
                //文件不保存创建一个文件
                FStream = new FileStream(strFileName, FileMode.Create);
                SPosition = 0;
            }
            try
            {
                //打开网络连接
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.newxing.com/download/" + file);
                if (SPosition > 0)
                    myRequest.AddRange((int)SPosition);//设置Range值
                                                       //向服务器请求,获得服务器的回应数据流
                Stream myStream = myRequest.GetResponse().GetResponseStream();
                //定义一个字节数据
                byte[] btContent = new byte[512];
                int intSize = 0;
                intSize = myStream.Read(btContent, 0, 512);
                while (intSize > 0)
                {
                    FStream.Write(btContent, 0, intSize);
                    intSize = myStream.Read(btContent, 0, 512);
                }
                //关闭流
                FStream.Close();
                myStream.Close();
                flag = true;//返回true下载成功
            }
            catch (Exception)
            {
                FStream.Close();
                flag = false;//返回false下载失败
            }
            return flag;
        }
    }
}
